package com.cloudfun.campusshare.service.impl;

import com.cloudfun.campusshare.configuration.property.UhomeProperties;
import com.cloudfun.campusshare.service.UhomeService;
import com.cloudfun.campusshare.util.haier.UhomeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * Created by Huqin on 2019/12/11
 */
@Service
@Slf4j
public class UhomeServiceImpl implements UhomeService {

    @Autowired
    private UhomeProperties uhomeProperties;

    @Autowired
    private RestTemplate restTemplate;

    @Override
    public String execute(String urlSuffix, String body) {
        String appId = uhomeProperties.getAppId();
        String appKey = uhomeProperties.getAppKey();
        String url = uhomeProperties.getBaseUrl() + urlSuffix;

        HttpHeaders headers = UhomeUtils.getBaseHeaders();
        headers.set("appId", appId);
        headers.set("appKey", appKey);
        long time = System.currentTimeMillis();
        headers.set("timestamp", String.valueOf(time));
        // add sign
        String sign = UhomeUtils.getSign(appId, appKey, String.valueOf(time), body, url);
        headers.set("sign", sign);

        HttpEntity<String> request = new HttpEntity<>(body, headers);
        ResponseEntity<String> response = restTemplate.postForEntity(url, request, String.class);
        log.info("execute result: " + response.getBody());

        return response.getBody();
    }

}
